package com.tiocloud.account.feature.login;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.mobile.auth.gatewayauth.Constant;
import com.nirvana.tools.jsoner.JSONUtils;
import com.tiocloud.account.TioAccount;
import com.tiocloud.account.data.AccountSP;
import com.umeng.umverify.UMResultCode;
import com.umeng.umverify.UMVerifyHelper;
import com.umeng.umverify.listener.UMTokenResultListener;
import com.umeng.umverify.model.UMTokenRet;
import com.watayouxiang.androidutils.mvp.BaseModel;
import com.watayouxiang.androidutils.tool.DialogHelper;
import com.watayouxiang.androidutils.widget.dialog.TioDialog;
import com.watayouxiang.db.dao.CurrUserTableCrud;
import com.watayouxiang.db.prefernces.TioDBPreferences;
import com.watayouxiang.httpclient.callback.TioCallback;
import com.watayouxiang.httpclient.callback.TioCallbackImpl;
import com.watayouxiang.httpclient.model.request.OnekeyRegisterReq;
import com.watayouxiang.httpclient.model.request.OnkeyLoginReq;
import com.watayouxiang.httpclient.model.request.UserCurrReq;
import com.watayouxiang.httpclient.model.response.OnkeyLoginResp;
import com.watayouxiang.httpclient.model.response.UserCurrResp;

import org.json.JSONObject;

import java.util.Map;

/**
 * 进app直接登录的场景
 */
public class OneKeyLoginActivity extends Activity {
    private static final String TAG = OneKeyLoginActivity.class.getSimpleName();

    private TextView mTvResult;
    private UMVerifyHelper mPhoneNumberAuthHelper;
    private UMTokenResultListener mTokenResultListener;
    private ProgressDialog mProgressDialog;
    private AuthPageConfig mUIConfig;

    public static void start(Context context) {
        if (!TioAccount.useOnkeyLogin) {
            LoginActivity.start(context);
            return;
        }
        Intent intent = new Intent(context, OneKeyLoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_login);
        sdkInit();
        mUIConfig = BaseUIConfig.init(this, mPhoneNumberAuthHelper);
        oneKeyLogin();
    }


    public void sdkInit() {
        mTokenResultListener = new UMTokenResultListener() {
            @Override
            public void onTokenSuccess(String s) {
//                ToastUtils.showShort("获取成功");
                hideLoadingDialog();
                UMTokenRet tokenRet = null;
                try {
                    tokenRet = UMTokenRet.fromJson(s);
                    if (UMResultCode.CODE_START_AUTHPAGE_SUCCESS.equals(tokenRet.getCode())) {
                        Log.i("TAG", "唤起授权页成功：" + s);
                    }

                    if (UMResultCode.CODE_GET_TOKEN_SUCCESS.equals(tokenRet.getCode())) {
                        Log.i("TAG", "获取token成功：" + s);
                        getResultWithToken(tokenRet.getToken());
                        mUIConfig.release();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onTokenFailed(String s) {
//                ToastUtils.showShort("获取失败："+s);
                Log.e(TAG, "获取token失败：" + s);
                hideLoadingDialog();
                UMTokenRet tokenRet = null;
                mPhoneNumberAuthHelper.quitLoginPage();
                try {
                    tokenRet = UMTokenRet.fromJson(s);
                    ToastUtils.showShort(tokenRet.getMsg());
                    if (UMResultCode.CODE_ERROR_USER_CANCEL.equals(tokenRet.getCode())) {
                        LoginActivity.start(OneKeyLoginActivity.this);
                        finish();
                    } else {
//                        Toast.makeText(getApplicationContext(), "一键登录失败切换到其他登录方式", Toast.LENGTH_SHORT).show();
//                        Intent pIntent = new Intent(OneKeyLoginActivity.this, MessageActivity.class);
//                        startActivityForResult(pIntent, 1002);
                        LoginActivity.start(OneKeyLoginActivity.this);
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mUIConfig.release();
            }
        };
        mPhoneNumberAuthHelper = UMVerifyHelper.getInstance(this, mTokenResultListener);
        mPhoneNumberAuthHelper.setAuthSDKInfo(TioAccount.UM_APPSECRY);
    }

    /**
     * 进入app就需要登录的场景使用
     */
    private void oneKeyLogin() {
        mPhoneNumberAuthHelper = UMVerifyHelper.getInstance(getApplicationContext(), mTokenResultListener);
        mUIConfig.configAuthPage();
        getLoginToken(15000);
    }

    /**
     * 拉起授权页
     *
     * @param timeout 超时时间
     */
    public void getLoginToken(int timeout) {
        mPhoneNumberAuthHelper.getLoginToken(this, timeout);
        showLoadingDialog("正在唤起授权页");
    }

    public void getResultWithToken(final String token) {
        LogUtils.e("token:" + token);
//        ToastUtils.showShort("成功");

//-------------
//        OnkeyLoginResp s = new OnkeyLoginResp();
//        s.setToken(token);
//        Intent intent = new Intent(OneKeyLoginActivity.this, InputNickActivity.class);
//        intent.putExtra("onkey", s);
//        startActivity(intent);
//        ActivityUtils.finishAllActivities();
        OnkeyLoginReq onkeyLoginReq = new OnkeyLoginReq(token, TioAccount.UM_APPKEY);
        onkeyLoginReq.setCancelTag(this);
        onkeyLoginReq.post(new TioCallback<OnkeyLoginResp>() {
            @Override
            public void onTioSuccess(OnkeyLoginResp s) {
                LogUtils.e("onkey:==>"+s);
                if (s == null){
                    loginStep2();
                }else {
                    s.setToken(token);
//                    inputNick(s);
                    Intent intent = new Intent(OneKeyLoginActivity.this, InputNickActivity.class);
                    intent.putExtra("onkey", s);
                    startActivity(intent);
                    ActivityUtils.finishAllActivities();
                }
            }

            @Override
            public void onTioError(String msg) {
                LogUtils.e("onkeyerr:==>"+msg);
            }
        });
//-------------------
//        ExecutorManager.run(new Runnable() {
//            @Override
//            public void run() {
//                final String result = getPhoneNumber(token);
//                OneKeyLoginActivity.this.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        mTvResult.setText("登陆成功：" + result);
//                        mPhoneNumberAuthHelper.quitLoginPage();
//                    }
//                });
//            }
//        });
    }

    //未注册用户，输入昵称
    private void inputNick(OnkeyLoginResp onkeyLoginResp) {
        hideLoadingDialog();

        new InputNickDialog(new InputNickDialog.OnBtnListener() {
            @Override
            public void onClickPositive(View view, String submitTxt, InputNickDialog dialog) {
                if (TextUtils.isEmpty(submitTxt))
                    submitTxt = null;
                toRegiest(submitTxt, onkeyLoginResp);
//                postCreateGroup(submitTxt, uidArray, dialog);
            }
        }).show_unCancel(this);
    }

    private void toRegiest(String submitTxt, OnkeyLoginResp onkeyLoginResp) {
        OnekeyRegisterReq onekeyRegisterReq =
                new OnekeyRegisterReq(onkeyLoginResp.getTempId(), onkeyLoginResp.getToken(), submitTxt);
        onekeyRegisterReq.setCancelTag(this);
        onekeyRegisterReq.post(new TioCallback<String>() {
            @Override
            public void onTioSuccess(String s) {
                loginStep2();
            }

            @Override
            public void onTioError(String msg) {

            }
        });
    }

    private void loginStep2() {
        // 获取用户信息
        new UserCurrReq().setCancelTag(this).get(new TioCallbackImpl<UserCurrResp>() {
            @Override
            public void onTioSuccess(UserCurrResp userCurrResp) {
//                proxy.onSuccess(userCurrResp);
//                proxy.onFinish();
                login(userCurrResp, userCurrResp.loginname);
            }

            @Override
            public void onTioError(String msg) {
                ToastUtils.showShort(msg);
//                proxy.onFailure(msg);
//                proxy.onFinish();
            }
        });
    }

    public static void login(UserCurrResp currInfo, String account) {
        // 存储登录名
        AccountSP.putLoginName(account);
        // 存储当前uid
        TioDBPreferences.saveCurrUid(currInfo.id);
        // 存储用户信息
        CurrUserTableCrud.insert(currInfo);
        // 打开主页
        TioAccount.getBridge().startMainActivity(Utils.getApp());
        // 关闭其他页面
        ActivityUtils.finishAllActivities();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1002) {
            if (resultCode == 1) {
                mTvResult.setText("登陆成功：" + data.getStringExtra("result"));
            } else {
                //模拟的是必须登录 否则直接退出app的场景
                finish();
            }
        }
    }


    public void showLoadingDialog(String hint) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        }
        mProgressDialog.setMessage(hint);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
    }

    public void hideLoadingDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mUIConfig.onResume();
    }
}
